# -*- coding: utf-8 -*-
from django.http import HttpResponse, HttpResponseRedirect
from django.db import models
from django.db.models import Q
from django.views.decorators.cache import cache_page
from opengov.govtrack.models import *
from opengov.util.breadcrumb import breadcrumb_from_objects
from opengov.util.comments_extra import post_comment
from django.contrib import comments
from django.contrib.comments.models import Comment
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
import codecs


#@cache_page(60 * 60)
def govtrack_index(request):
	breadcrumb = breadcrumb_from_objects([{"title": "Govtrack", "url": "/govtrack/"}])
	page_title = u"Govtrack - aktuell information om regeringsinitiativ" 
	current = "govtrack"

	komdir = Kommittedirektiv.objects.select_related("sfser").order_by("-regeringssammantrade", "-dir_nr")[:10]
	lagreferenser = []
	for item in komdir:
		for ref in item.sfser.all():
			if len(lagreferenser) < 12:
				lagreferenser.append(ref)

	utredningar = Utredning.objects.filter(redovisas__gte=datetime.today()).order_by("redovisas")[:8]

	return render_to_response('govtrack_index.html', locals(), context_instance=RequestContext(request))



@cache_page(60 * 60)
def govtrack_komdir_index(request):
	items = Kommittedirektiv.objects.all().order_by("-regeringssammantrade", "-dir_nr")[:20]
	breadcrumb = breadcrumb_from_objects([{"title": "Govtrack", "url": "/govtrack/"}, {"title": "Kommittédirektiv", "url": "/govtrack/dir/"}])
	page_title = "Kommittédirektiv"
	current = "govtrack"

	feeds = [{"title": u"Senaste kommittédirektiven", "href":"/govtrack/dir/feed/"}]

	return render_to_response('govtrack_komdir_index.html', locals())


def govtrack_komdir_feed(request):
	"""Skapa en dynamisk feed i samma stil som Google's gdata"""

	feed = AtomFeed()
	feed.url = request.build_absolute_uri()
	feed.title = u"Kommittédirektiv"

	if request.method == 'GET':
		maxresults = 20
		try:
			# Ord i rubrik (minst tre tecken)
			if len(request.GET["q"])>2 and len(request.GET["q"]) < 200:
				q_rubrik = Q(rubrik__icontains=request.GET["q"])
				maxresults = 50
				feed.title = feed.title + " med text '" + request.GET["q"] + "'"
			else:
				raise 
		except:
			q_rubrik = Q()

		try:
			#från datum
			mindate = datetime.strptime(request.GET["published-min"], "%Y-%m-%d")
			q_publishedmin = Q(regeringssammantrade__gte=mindate)
			maxresults = 500
			feed.title = feed.title + u" från datum %s-%s-%s" % (mindate.year, mindate.month, mindate.day)
		except:
			q_publishedmin = Q()

		try:
			#till datum
			maxdate = datetime.strptime(request.GET["published-max"], "%Y-%m-%d")
			q_publishedmax = Q(regeringssammantrade__lte=maxdate)
			maxresults = 50
		except:
			q_publishedmax = Q()

			try:
				q_departement = Q(departement__code__iexact=request.GET["departement"])
				maxresults = 50
				feed.title = feed.title + " med departementskod " + request.GET["departement"]
			except:
				q_departement = Q()


			feed.entries = [item.to_atomentry() for item in Kommittedirektiv.objects.filter(q_rubrik, q_publishedmax, q_publishedmin, q_departement)[:maxresults]]
			if len(feed.entries) > 0:
				feed.updated = feed.entries[0].updated
			

		return render_to_response('atom_feed.xml', locals())


@cache_page(60 * 60)
def govtrack_komdir_single(request, dir_nr):
	item = get_object_or_404(Kommittedirektiv, dir_nr=dir_nr)
	breadcrumb = breadcrumb_from_objects([{"title": "Govtrack", "url": "/govtrack/"}, {"title": "Kommittédirektiv", "url": "/govtrack/dir/"}])
	page_title = "Dir. " + item.dir_nr + " " + item.rubrik 
	current = "govtrack"
	utredning = None
	if item.utredning.all():
		utredning = item.utredning.all()[0]

	content_fragment = u""
	f = codecs.open(item.content_fragment_path(), "r", "utf-8")
	content_fragment = f.read()
	f.close()

	#default form
	form = comments.get_form()(item, None)

	return render_to_response('govtrack_komdir_single.html', locals())


@cache_page(60 * 60)
def govtrack_komdir_ical(request, dir_nr):
	item = get_object_or_404(Kommittedirektiv, dir_nr=dir_nr)
	return render_to_response('govtrack_komdir_ical.html', locals(), mimetype='text/calendar')


@cache_page(60 * 60)
def govtrack_sfs_single(request, sfsnummer):
	item = get_object_or_404(SFSReferens, sfsnummer=sfsnummer)
	breadcrumb = breadcrumb_from_objects([{"title": "Govtrack", "url": "/govtrack/"}, {"title": "SFS", "url": "/govtrack/sfs/"}])
	page_title = item.rubrik 
	current = "govtrack"

	feeds = [{"title": u"Referenser till SFS %s" % sfsnummer, "href":"/govtrack/sfs/feed/%s" % sfsnummer}]

	return render_to_response('govtrack_sfs_single.html', locals())


def govtrack_sfs_feed(request, sfsnummer):
	feed = AtomFeed()
	feed.url = request.build_absolute_uri()
	feed.title = u"Referenser till SFS %s" % sfsnummer

	try:
		sfs = SFSReferens.objects.get(sfsnummer=sfsnummer)
	except SFSReferens.DoesNotExist:
		sfs = None

	if sfs:
		maxresults = 50
		komdir = Kommittedirektiv.objects.filter(pk__in=[dir.id for dir in sfs.kommittedirektiv.all()])[:maxresults]
		
		feed.entries = [item.to_atomentry() for item in komdir]

	return render_to_response('atom_feed.xml', locals())



@cache_page(60 * 60)
def govtrack_departement_single(request, sou_slug):
	item = get_object_or_404(Departement, sou_slug=sou_slug)
	breadcrumb = breadcrumb_from_objects([{"title": "Govtrack", "url": "/govtrack/"}, {"title": "Departement", "url": "/govtrack/dep/"}])
	page_title = item.name 
	current = "govtrack"
	feeds = [{"title": u"Senaste kommittédirektiv från %s" % item.name, "href":"/govtrack/dir/feed/?departement=%s" % item.code}]

	komdir = Kommittedirektiv.objects.filter(departement=item)[:20]

	return render_to_response('govtrack_departement_single.html', locals())



@cache_page(60 * 60)
def govtrack_prop_single(request, nummer):
	item = get_object_or_404(Proposition, nummer=nummer)
	breadcrumb = breadcrumb_from_objects([{"title": "Govtrack", "url": "/govtrack/"}, {"title": "Propositioner", "url": "/govtrack/prop/"}])
	page_title = item.rubrik 
	current = "govtrack"

	return render_to_response('govtrack_prop_single.html', locals())

@cache_page(60 * 60)
def govtrack_utredning_index(request):
	items = Utredning.objects.all().order_by("-id")[:10]
	breadcrumb = breadcrumb_from_objects([{"title": "Govtrack", "url": "/govtrack/"},])
	page_title = u"Utredningar" 
	current = "govtrack"

	return render_to_response('govtrack_utredning_index.html', locals())


@cache_page(60 * 60)
def govtrack_utredning_single(request, departementskod, nummer):
	utredningsnummer = departementskod + " " + nummer
	item = get_object_or_404(Utredning, nummer=utredningsnummer)
	breadcrumb = breadcrumb_from_objects([{"title": "Govtrack", "url": "/govtrack/"}, {"title": "Utredningar", "url": "/govtrack/utredning/"}])
	page_title = item.rubrik 
	current = "govtrack"
	
	if request.method == "POST":
		return post_comment(request, None, item, locals(), "catalog_item.html")

	#default form
	form = comments.get_form()(item, None)

	return render_to_response('govtrack_utredning_single.html', locals())


@cache_page(60 * 60)
def govtrack_utredning_ical(request, departementskod, nummer):
	utredningsnummer = departementskod + " " + nummer
	item = get_object_or_404(Utredning, nummer=utredningsnummer)
	return render_to_response('govtrack_utredning_ical.html', locals(), mimetype='text/calendar')



@cache_page(60 * 60)
def govtrack_celex_single(request, celexnummer):
	item = get_object_or_404(CelexReferens, celexnummer=celexnummer)
	breadcrumb = breadcrumb_from_objects([{"title": "Govtrack", "url": "/govtrack/"},])
	if len(item.rubrik) == 0:
		item.rubrik = item.celexnummer

	page_title = u"Referenser till " + item.rubrik
	current = "govtrack"

	return render_to_response('govtrack_celex_single.html', locals())
